﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace AISFMIOperator
{
    public class Region
    {
        public Region()
        { }

        public int RegionID
        { get; set; }

        public string RegionName
        { get; set; }

        public void Save()
        {
            SqlCommand command = new SqlCommand("CreateRegion");
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("@region_name", SqlDbType.VarChar, 256).Value = RegionName;
            command.Parameters.Add("@region_id", SqlDbType.Int).Direction = ParameterDirection.Output;
            SQLDBLayer.ExecSPNonQuery(command);
            this.RegionID = (int)command.Parameters["@region_id"].Value;
        }

        public void Update()
        {
            SqlCommand command = new SqlCommand("UpdateRegion");
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("@region_name", SqlDbType.VarChar, 256).Value = RegionName;
            command.Parameters.Add("@region_id", SqlDbType.Int).Value = RegionID;
            SQLDBLayer.ExecSPNonQuery(command);
        }

        public void Delete()
        {
            SqlCommand command = new SqlCommand("DeleteRegion");
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add("@region_id", SqlDbType.Int).Value = RegionID;
            SQLDBLayer.ExecSPNonQuery(command);
        }

        public static List<Region> GetAllRegions()
        {
            DataTable table = new DataTable();
            List<Region> objects = new List<Region>();
            SqlCommand command = new SqlCommand("GetRegions");
            command.CommandType = CommandType.StoredProcedure;

            table = SQLDBLayer.ExecSPTable(command);

            foreach (DataRow row in table.Rows)
            {                
                Region region = new Region();
                region.RegionID = (int)row["region_id"];
                region.RegionName = row["region_name"].ToString();

                objects.Add(region);
            }

            return objects;
        }
    }
}
